package com.qf.homeworkssm.utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * 文本文件追加器
 */
public class QfFileAppender {

    /**
     * 文本文件的绝对路径
     */
    private String filepath;

    private BufferedWriter bufferedWriter;

    public QfFileAppender(String filepath) throws IOException {
        this.filepath = filepath;

        // 初始化 bufferedWriter ，目的是让每个 QfFileAppender 对象只有一个 bufferedWriter 对象，避免重复创建
        this.bufferedWriter = new BufferedWriter(new FileWriter(filepath, true));
    }

    /**
     * 把 data 追加到 文本文件中
     * @param data List<String>
     * @return
     */
    public Integer appendListToFile(List<String> data) throws IOException {

        int count = 0;
        for (String line : data) {
            bufferedWriter.write(line);
            bufferedWriter.newLine();
            count++;
        }

        return count;
    }

    /**
     * 关闭资源
     */
    public void close() throws IOException {
        bufferedWriter.close();
    }




}
